package com.leoman.customer.controller;

import com.leoman.common.controller.common.GenericEntityController;
import com.leoman.common.core.Result;
import com.leoman.common.factory.DataTableFactory;
import com.leoman.common.service.Query;
import com.leoman.customer.entity.Customer;
import com.leoman.customer.entity.CustomerDemand;
import com.leoman.customer.service.CustomerDemandService;
import com.leoman.customer.service.CustomerService;
import com.leoman.customer.service.impl.CustomerServiceImpl;
import com.leoman.permissions.admin.entity.Admin;
import com.leoman.permissions.admin.service.AdminService;
import com.leoman.utils.DateUtils;
import com.leoman.utils.JsonUtil;
import org.apache.commons.lang.StringUtils;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.OutputStream;
import java.text.ParseException;
import java.util.*;

/**
 * 客户
 * Created by Daisy on 2016/12/27.
 */
@Controller
@RequestMapping(value = "admin/customer")
public class CustomerController extends GenericEntityController<Customer,Customer,CustomerServiceImpl> {

    @Autowired
    private CustomerService customerService;

    @Autowired
    private AdminService adminService;

    @Autowired
    private CustomerDemandService customerDemandService;

    @RequestMapping(value = "/index")
    public String index(Model model){
        List<Admin> adminList = adminService.findByRoleId(3l);//获取所有新增客户需求权限的管理员
        model.addAttribute("adminList", adminList);
        return "customer/customer_list";
    }

    /**
     * 列表
     * @return
     */
    @RequestMapping(value = "/list", method = RequestMethod.POST)
    @ResponseBody
    public Map<String, Object> list(HttpServletRequest request, String searchContent, String grade, String createDate, Integer draw, Integer start, Integer length) {
        //只获取当前分配给当前登录的管理员的需求
        Long adminId = null;
        Admin loginAdmin = getSessionAdmin(request);
        if(loginAdmin.getRoleId() == 3){
            adminId = loginAdmin.getId();
        }

        int pageNum = getPageNum(start, length);
        Page page = customerService.findPage(adminId, searchContent, grade, createDate, pageNum, length);
        return DataTableFactory.fitting(draw, page);
    }

    /**
     * 编辑
     * @param id
     * @param model
     * @return
     */
    @RequestMapping(value = "/edit")
    public String edit(Long id, Model model){

        if(id != null){
            Customer customer = customerService.queryByPK(id);
            model.addAttribute("customer", customer);
        }

        return "customer/customer_add";
    }

    /**
     * 保存
     * @param customer
     * @return
     */
    @RequestMapping(value = "/save", method = RequestMethod.POST)
    @ResponseBody
    public Result save(Customer customer) {

        Result result = customerService.saveCustomer(customer);
        return result;
    }

    /**
     * 删除
     * @return
     */
    @RequestMapping(value = "/delete", method = RequestMethod.POST)
    @ResponseBody
    public Result del(String ids) {
        String[] idArr = JsonUtil.json2Obj(ids,String[].class);
        for (String id : idArr) {
            if(StringUtils.isNotEmpty(id)){
                Customer customer = customerService.queryByPK(Long.valueOf(id));
                if(customer != null){
                    customer.setStatus(1);
                    customerService.save(customer);
                }
            }
        }

        return Result.success();
    }

    /**
     * 详情
     * @param id
     * @param model
     * @return
     */
    @RequestMapping(value = "/info")
    public String info(Long id, Model model){

        if(id != null){
            Customer customer = customerService.queryByPK(id);
            List<CustomerDemand> demandList = customerDemandService.findByCustomerId(id);
            model.addAttribute("customer", customer);
            model.addAttribute("demandList", demandList);
        }

        return "customer/customer_info";
    }

    /**
     * 新增需求
     * @param model
     * @return
     */
    @RequestMapping(value = "/addDemand")
    public String addDemand(Long customerId, Model model){
        model.addAttribute("customerId", customerId);
        return "customer/demand_add";
    }

    /**
     * 保存需求
     * @return
     */
    @RequestMapping(value = "/saveDemand", method = RequestMethod.POST)
    @ResponseBody
    public Result saveDemand(CustomerDemand customerDemand) {

        customerDemandService.save(customerDemand);
        return Result.success();
    }

    /**
     * 消息提醒页面
     * @param model
     * @return
     */
    @RequestMapping(value = "/messageIndex")
    public String messageIndex(Model model){
        return "customer/customer_demand_list";
    }

    /**
     * 列表
     * @return
     */
    @RequestMapping(value = "/messageList", method = RequestMethod.POST)
    @ResponseBody
    public Map<String, Object> messageList(HttpServletRequest request, String searchContent, Integer draw, Integer start, Integer length) throws ParseException {
        int pageNum = getPageNum(start, length);
        Query query = Query.forClass(CustomerDemand.class, customerDemandService);
        query.setPagenum(pageNum);
        query.setPagesize(length);

        //只查看下次联系时间为今天的需求
        query.between("nextTime", DateUtils.startOfTodDay(), DateUtils.endOfTodDay());

        //只获取当前分配给当前登录的管理员的需求
        Admin loginAdmin = getSessionAdmin(request);
        if(loginAdmin != null){
            List<Long> customerIdList = new ArrayList<>();
            Query queryC = Query.forClass(Customer.class, customerService);
            queryC.eq("status", 0);
            queryC.eq("adminId", loginAdmin.getId());
            List<String> propertyName = Arrays.asList(new String[]{"name","mobile","qq"});
            queryC.orLike(propertyName, searchContent);
            List<Customer> customerList = customerService.queryAll(queryC);
            if(customerList == null || customerList.size() == 0){
                customerIdList.add(-1l);
            }else{
                for (Customer cu:customerList) {
                    customerIdList.add(cu.getId());
                }
            }
            query.in("customerId", customerIdList);
        }
        Page<CustomerDemand> page = customerDemandService.queryPage(query);

        for (CustomerDemand cd:page.getContent()) {
            //获取需求对应的客户
            Customer customer = customerService.queryByPK(cd.getCustomerId());
            //设置客户对应的操作员
            if(customer.getAdminId() != null){
                Admin admin = adminService.queryByPK(customer.getAdminId());
                customer.setAdmin(admin);
            }
            cd.setCustomer(customer);
        }
        return DataTableFactory.fitting(draw, page);
    }

    /**
     * 导出
     * @param request
     * @param response
     * @param searchContent
     * @return
     * @throws Exception
     */
    @RequestMapping("/exportExl")
    public void exportExl(HttpServletRequest request,
                          HttpServletResponse response,
                          String searchContent) throws Exception {

        Query query = Query.forClass(Customer.class, customerService);
        query.eq("status", 0);

        List<String> propertyName = Arrays.asList(new String[]{"name","mobile","qq"});
        query.orLike(propertyName, searchContent);

        //只获取当前分配给当前登录的管理员的需求
        Admin loginAdmin = getSessionAdmin(request);
        if(loginAdmin.getRoleId() == 3){
            query.eq("adminId", loginAdmin.getId());
        }

        List<Customer> list = customerService.queryAll(query);

        for (Customer customer:list) {
            //设置客户的操作员
            if(customer.getAdminId() != null){
                Admin admin = adminService.queryByPK(customer.getAdminId());
                customer.setAdmin(admin);
            }
            //设置客户的最新一条需求
            List<CustomerDemand> demandList = customerDemandService.queryTop("id", "customerId", customer.getId() , false, 1);
            if(demandList != null && demandList.size() > 0){
                customer.setDemand(demandList.get(0));
            }
        }

        Workbook wb = new HSSFWorkbook();

        // 创建sheet对象
        Sheet sheet1 = wb.createSheet("sheet1");

        Row header = sheet1.createRow(0);
        String [] titleArr = {"需求号","客户姓名","客户手机号","最后联系时间","下次联系时间","重要等级","分配操作员"};
        for(int i=0; i<6; i++){
            Cell title = header.createCell(i);
            title.setCellValue(titleArr[i]);
            sheet1.setColumnWidth(i, 16 * 256);
        }

        for(int i=0; i<list.size(); i++){

            Customer cu = list.get(i);

            Row row = sheet1.createRow(i+1);

            Cell cell0 = row.createCell(0);
            cell0.setCellValue(cu.getDemandNo());//需求号

            Cell cell1 = row.createCell(1);
            cell1.setCellValue(cu.getName());//客户姓名

            Cell cell2 = row.createCell(2);
            cell2.setCellValue(cu.getMobile());//客户手机号

            Cell cell3 = row.createCell(3);
            if(cu.getDemand() != null && cu.getDemand().getCreateDate() != null){
                Date createDate = new Date(cu.getDemand().getCreateDate());
                String createStr = DateUtils.dateToString(createDate, "yyyy-MM-dd HH:mm");
                cell3.setCellValue(createStr);//最近联系时间
            }

            Cell cell4 = row.createCell(4);
            if(cu.getDemand() != null && cu.getDemand().getNextTime() != null){
                Date nextTime = new Date(cu.getDemand().getNextTime());
                String nextStr = DateUtils.dateToString(nextTime, "yyyy-MM-dd");
                cell4.setCellValue(nextStr);//下次联系时间
            }

            Cell cell5 = row.createCell(5);
            if(cu.getDemand() != null){
                cell5.setCellValue("FAIL".equals(cu.getDemand().getGrade())?"战败":cu.getDemand().getGrade());//等级
            }

            Cell cell6 = row.createCell(6);
            if(cu.getAdmin() != null){
                cell6.setCellValue(cu.getAdmin().getName());//分配操作员
            }
        }

        OutputStream os = response.getOutputStream();// 取得输出流
        response.setContentType("application/x-download");
        response.setHeader("Content-disposition", "attachment;filename=customer.xls");
        wb.write(os);
        // 关闭文件流
        os.close();

    }


}
